package connection;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Connection extends JInternalFrame {

	public Socket fics;
	
	public BufferedReader br;

	String s;

	Reader read;

	JPanel pan;

	JButton send;

	JButton pass;

	JTextField in = new JTextField();

	JPasswordField passF;

	BufferedWriter bw;

	JFrame a;

	public Connection() {
		super("Console", true, // resizable
				true, // closable
				true, // maximizable
				true);// iconifiable
		try {

			fics = new Socket("freechess.org", 5000);
			bw = new BufferedWriter(new OutputStreamWriter(fics
					.getOutputStream()));
			pan = new JPanel();
			send = new JButton("Send");
			pass = new JButton("Pass");
			passF = new JPasswordField(10);
			br = new BufferedReader(new InputStreamReader(fics.getInputStream()));

			ActionListener lst = new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					buttAction();

				}
			};
			send.addActionListener(lst);
			in.setActionCommand("\n");
			in.addActionListener(lst);

			ActionListener lst2 = new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					passField();
				}
			};
			pass.addActionListener(lst2);

			ActionListener lst3 = new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try {
						bw.write(new String(passF.getPassword()) + "\n");
						bw.flush();
						a.setVisible(false);
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			};

			passF.setActionCommand("\n");
			passF.addActionListener(lst3);

			read = new Reader(br,bw);
			read.start();

			pan.setLayout(new BorderLayout());
			pan.add(read.textPan(), BorderLayout.NORTH);
			pan.add(in, BorderLayout.CENTER);
			pan.add(pass, BorderLayout.EAST);
			read.con.setPreferredSize(new Dimension(500, 300));
			this.add(pan);
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		this.pack();
	}

	public void buttAction() {
		try {
			bw.write(in.getText() + "\n");
			bw.flush();
			in.setText("");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void passField() {
		a = new JFrame("Password");
		a.setVisible(true);
		a.add(passF);
		passF.setPreferredSize(new Dimension(100, 20));
		a.setLocationRelativeTo(in);
		a.pack();
	}
	
	public boolean isConnected()
	{
		if(fics!=null)
		{
			return true;
		}
		return false;
	}
}
